local Msg = require("core.Msg")
local BagLogic = require("bag.BagLogic")
local Grid = require("bag.Grid")
local ChengjiuExcel = require("excel.chengjiu").chengjiu
local GroupExcel = require("excel.chengjiu").group
local HeroLogic = require("hero.HeroLogic")
local RoleSystemLogic = require("roleSystem.RoleSystemLogic")
local RoleDBLogic = require("role.RoleDBLogic")
local RoleSystemDefine = require("roleSystem.RoleSystemDefine")
local ObjHuman = require("core.ObjHuman")
local CombatObj = require("combat.CombatObj")
local CombatDefine = require("combat.CombatDefine")
local ChengjiuDefine = require("chengjiu.ChengjiuDefine")
local CombatPosLogic = require("combat.CombatPosLogic")
local RoleAttr = require("role.RoleAttr")
local GuideLogic = require("guide.GuideLogic")
local DB = require("common.DB")
local LuaMongo = _G.lua_mongo

--[[
human.db.chengjiu = {}
human.db.chengjiu.task = {}
human.db.chengjiu.group = {}
human.db.chengjiu.task[taskID] = state              -- 单个任务对应完成状态
human.db.chengjiu.type[taskType] = cnt              -- 任务类型对应完成次数
human.db.chengjiu.group[groupID] = state            -- 任务组对应完成状态
human.db.chengjiu.privilege[privilege] = value      -- 玩家已获取奖励累积
human.db.chengjiu.attr[key] = value                 -- 玩家已获取属性奖励累计
]]

local CJ_TASK_STATE_0 = 0               -- 任务状态 未达成
local CJ_TASK_STATE_1 = 1               -- 任务状态 可解封
local CJ_TASK_STATE_2 = 2               -- 任务状态 已解封
local CJ_GROUP_STATE_0 = 0              -- 任务组状态 未开放
local CJ_GROUP_STATE_1 = 1              -- 任务组状态 已开放
local CJ_GROUP_STATE_2 = 2              -- 任务组状态 已达成

local CJ_PARAM_TYPE = {}
function initAfterHot()
    for k,v in pairs(ChengjiuExcel) do
        CJ_PARAM_TYPE[v.type] = v.paramType
	end
end

local function makePrivilegeNet(data,net,type)
    if type then
        local lenth = #data
        for i = 1,lenth do
            net[0] = net[0] + 1
            net[net[0]].key = data[i][1]
            net[net[0]].value = data[i][2]
        end
    else
        if data.privilege then
            for k,v in pairs(data.privilege) do
                net[0] = net[0] + 1
                net[net[0]].key = k
                net[net[0]].value = v
            end
        end
        if data.attrs then
            for k,v in pairs(data.attrs) do
                net[0] = net[0] + 1
                net[net[0]].key = k
                net[net[0]].value = v
            end
        end
    end
end

local function makeChengjiuNet(human,config,net,id)
    net.groupID = config.group
    net.taskID = id
    net.desc = config.desc
    net.curCnt = 0
    net.state = CJ_TASK_STATE_0

    if human.db.chengjiu.type and human.db.chengjiu.type[config.type] then
        net.curCnt = human.db.chengjiu.type[config.type]
    end

    if human.db.chengjiu.task and human.db.chengjiu.task[id] then
        net.state = human.db.chengjiu.task[id]
    end

    net.maxCnt = config.param
    net.goDot = 0
    net.privilege[0] = 0
    makePrivilegeNet(config.privilege,net.privilege,1)
    makePrivilegeNet(config.attr,net.privilege,1)
    net.panelID = config.panelID
    local len = #config.items
    for i = 1,len do
        Grid.makeItem(net.items[i],config.items[i][1],config.items[i][2])
    end
    net.items[0] = len
   
    local groupConfig = GroupExcel[config.group]
    if config.group <= 4 and human.chengJiuGo and human.chengJiuGo[config.group] and human.chengJiuGo[config.group][id] then
    elseif  config.group <= 4 and net.state == CJ_TASK_STATE_0 and human.db.lv >= groupConfig.lv then
        net.goDot = 1
    end
end

local function makeChengjiuList(human,config,net,id)
    net.groupID = id
    net.lv = config.lv
    net.state = CJ_GROUP_STATE_1
    if human.db.chengjiu.group and human.db.chengjiu.group[id] then
        net.state = human.db.chengjiu.group[id]
    end
    if config.lv > human.db.lv then
        net.state = CJ_GROUP_STATE_0
    end
    net.dot = 0
    for _,taskId in pairs(config.member) do
        if human.db.chengjiu.task and human.db.chengjiu.task[taskId] == 1 then
            net.dot = 1
            break
        end
    end
    local state = CJ_TASK_STATE_0
    if id <= 4 and net.dot == 0 and net.state == CJ_GROUP_STATE_1 then
        for _,taskId in pairs(config.member) do
            if human.chengJiuGo and  human.chengJiuGo[id] and human.chengJiuGo[id][taskId] then
            else
                state = CJ_TASK_STATE_0

                if human.db.chengjiu and human.db.chengjiu.task and human.db.chengjiu.task[taskId] then
                    state = human.db.chengjiu.task[taskId]
                end                
               
                if state == CJ_TASK_STATE_0 then
                    net.dot = 1
                    break
                end
            end
        end
    end
end

function chenJiuGo(human, groupID, taskID) 
    human.chengJiuGo = human.chengJiuGo or {}

    human.chengJiuGo[groupID] =  human.chengJiuGo[groupID] or {}
    human.chengJiuGo[groupID][taskID] = 1
    RoleSystemLogic.onDot(human, RoleSystemDefine.ROLE_SYS_ID_2001)
end

function query(human,groupID,type)
    if groupID == 0 then
        groupID = 1
        for k,v in pairs(GroupExcel) do
            if human.db.chengjiu.group and human.db.chengjiu.group[k] == nil then
                groupID = k
                break
            end
        end
    end

	local msgRet = Msg.gc.GC_CHENGJIU_QUERY
    msgRet.groupID = groupID
    msgRet.type = type
	local taskLen = 0
	for k,v in pairs(ChengjiuExcel) do
        if groupID == v.group then
            taskLen = taskLen + 1
            makeChengjiuNet(human,v,msgRet.task[taskLen],k)
        end
	end
	msgRet.task[0] = taskLen

    local listLen = 0
    for k,v in pairs(GroupExcel) do
        listLen = listLen + 1
        makeChengjiuList(human,v,msgRet.list[listLen],k)
	end
	msgRet.list[0] = listLen
    msgRet.tips[0] = 0
    makePrivilegeNet(human.db.chengjiu,msgRet.tips)

	Msg.send(msgRet,human.fd)
end


function isFinish(human,taskID)
    local config = ChengjiuExcel[taskID]
    if not config then return end
    local groupConfig = GroupExcel[config.group]
    if not groupConfig then return end

    -- 任务校验错误
	if human.db.chengjiu.task == nil or 
       human.db.chengjiu.task[taskID] == nil or 
       config == nil or
       groupConfig.lv > human.db.lv then
        return 
    end

    -- 当前任务类型达成次数不足
    if human.db.chengjiu.type == nil or 
       human.db.chengjiu.type[config.type] == nil then
        return
    end

    -- 当前领取任务状态不为可领取
    if human.db.chengjiu.task[taskID] ~= CJ_TASK_STATE_1 then
        return 
    end

    return true
end


function getReward(human,taskID)
    local config = ChengjiuExcel[taskID]
    if not config then return end
    local groupConfig = GroupExcel[config.group]
    if not groupConfig then return end
    
    -- 任务校验错误
	if human.db.chengjiu.task == nil or 
       human.db.chengjiu.task[taskID] == nil or 
       config == nil or
       groupConfig.lv > human.db.lv then
        return 
    end

    -- 当前任务类型达成次数不足
    if human.db.chengjiu.type == nil or 
       human.db.chengjiu.type[config.type] == nil then
        return
    end

    -- 当前领取任务状态不为可领取
    if human.db.chengjiu.task[taskID] ~= CJ_TASK_STATE_1 then
        return 
    end

    human.db.chengjiu.task[taskID] = CJ_TASK_STATE_2

    local isOver = 1
    for k,v in pairs(ChengjiuExcel) do
        if v.group == config.group then
            -- 同组任务没有完成
            if human.db.chengjiu.task[k] == nil or 
               human.db.chengjiu.task[k] ~= CJ_TASK_STATE_2 then
                isOver = 0
                break
            end
        end
    end

    if isOver == 1 then
        human.db.chengjiu.group = human.db.chengjiu.group or {}
        human.db.chengjiu.group[config.group] = CJ_GROUP_STATE_2
    end

    -- 给道具奖励
    for i = 1,#config.items do
        BagLogic.addItem(human, config.items[i][1],config.items[i][2], "chengjiu")
    end
	

    -- 给特权奖励
    for _,v in pairs(config.privilege) do
        human.db.chengjiu.privilege = human.db.chengjiu.privilege or {}
        human.db.chengjiu.privilege[v[1]] = human.db.chengjiu.privilege[v[1]] or 0
        human.db.chengjiu.privilege[v[1]] = human.db.chengjiu.privilege[v[1]] + v[2]
        addPrivilegeDo(human,v[1])
    end

    -- 给属性奖励
    for k,v in pairs(config.attr) do
        human.db.chengjiu.attrs = human.db.chengjiu.attrs or {}
        human.db.chengjiu.attrs[v[1]] = human.db.chengjiu.attrs[v[1]] or 0
        human.db.chengjiu.attrs[v[1]] = human.db.chengjiu.attrs[v[1]] + v[2]
        RoleAttr.cleanHeroAttrCache(human)
    end

    local msgRet = Msg.gc.GC_CHENGJIU_GET
    msgRet.taskID = taskID
    Msg.send(msgRet,human.fd)
    --query(human,config.group)
    
    GuideLogic.setDoSpecialGuide(human, GuideLogic.SKIPTYPE_JUMP_JIEFENG_BAOJU)
    RoleSystemLogic.onDot(human, RoleSystemDefine.ROLE_SYS_ID_2001)
end

-- 回调
function onCallback(human,taskType,cnt)
    if CJ_PARAM_TYPE[taskType] == 1 then
        human.db.chengjiu.type = human.db.chengjiu.type or {}
        human.db.chengjiu.type[taskType] = human.db.chengjiu.type[taskType] or 0 
        human.db.chengjiu.type[taskType] = human.db.chengjiu.type[taskType] + cnt 
    else
        human.db.chengjiu.type = human.db.chengjiu.type or {}
        human.db.chengjiu.type[taskType] = cnt 
    end
    local touchCnt = human.db.chengjiu.type[taskType]
    for k,v in pairs(ChengjiuExcel) do
        local config = GroupExcel[v.group]
        if v.type == taskType and 
           human.db.lv >= config.lv and
           touchCnt >= v.param and 
           (human.db.chengjiu.task == nil or
           human.db.chengjiu.task[k] == CJ_TASK_STATE_0 or
           human.db.chengjiu.task[k] == nil) then

            human.db.chengjiu.task = human.db.chengjiu.task or {}
            human.db.chengjiu.task[k] = CJ_TASK_STATE_1
            RoleSystemLogic.onDot(human, RoleSystemDefine.ROLE_SYS_ID_2001)
            RoleSystemLogic.onDot(human, RoleSystemDefine.ROLE_SYS_ID_2002)
            
            local msgRet = Msg.gc.GC_CHENGJIU_SET
            msgRet.taskID = k
            msgRet.groupID = v.group
            msgRet.desc = v.desc
            Msg.send(msgRet,human.fd)
        end
    end
end

-- 检查任务
function checkTaskState(human)
    for k,v in pairs(ChengjiuExcel) do
        local config = GroupExcel[v.group]
        local touchCnt = 0
        if human.db.chengjiu.type and human.db.chengjiu.type[v.type] then
            touchCnt = human.db.chengjiu.type[v.type]
        end
        if human.db.lv >= config.lv and
           touchCnt >= v.param and 
           (human.db.chengjiu.task == nil or
           human.db.chengjiu.task[k] ~= CJ_TASK_STATE_2) then

            human.db.chengjiu.task = human.db.chengjiu.task or {}
            human.db.chengjiu.task[k] = CJ_TASK_STATE_1
            RoleSystemLogic.onDot(human, RoleSystemDefine.ROLE_SYS_ID_2001)
            local msgRet = Msg.gc.GC_DAILYSHARE_SET
            msgRet.type = 2
            msgRet.desc = v.desc
            Msg.send(msgRet,human.fd)
        end
    end
end
-- 回调
function onLvUp(human)
    checkTaskState(human)
end

function isDot(human)
    if not RoleSystemLogic.isOpen(human, RoleSystemDefine.ROLE_SYS_ID_2001) then
		return 
	end

    for i = 1, 4 do
        local needLv = GroupExcel[i].lv
        if needLv <= human.db.lv then
            for k, id in ipairs( GroupExcel[i].member) do
                if human.chengJiuGo and human.chengJiuGo[i] and human.chengJiuGo[i][id] then
                else
                    if human.db.chengjiu.task and human.db.chengjiu.task[id] and human.db.chengjiu.task[id] ~= CJ_TASK_STATE_0 then
                    else
                        return true
                    end
                    
                end  
            end
        end
    end

    if human.db.chengjiu.task == nil then
        return
    end
    for k,v in pairs(human.db.chengjiu.task) do
        if ChengjiuExcel[k] then
            local groupID = ChengjiuExcel[k].group
            local needLv = GroupExcel[groupID].lv
            if v == CJ_TASK_STATE_1 and human.db.lv >= needLv then
                return true
            end
        end
    end
    return
end

function onCallbackByUuid(uuid,taskType,cnt)
    local target = ObjHuman.onlineUuid[uuid]
	if target and target.fd then
		onCallback(target,taskType,cnt)
	else
		local fakeDB = RoleDBLogic.getDb(uuid)
		if fakeDB then
			local fakeHuman = {}
			fakeHuman.db = fakeDB
			if onCallback(fakeHuman,taskType,cnt) then
				ObjHuman.save(fakeHuman)
			end
		end
	end	
end

-- 计算特权
function addPrivilegeDo(human,privilege)
    -- 解锁援军
    if privilege == ChengjiuDefine.PRIVILEGE_TYPE_6 then
        CombatPosLogic.activeBackup(human)
    -- 解锁守护之龙
    elseif privilege == ChengjiuDefine.PRIVILEGE_TYPE_8 then
       RoleAttr.cleanHeroAttrCache(human)
    -- 增加栏位
    elseif privilege == ChengjiuDefine.PRIVILEGE_TYPE_1 then
	    HeroLogic.sendHeroBagCap(human)
    end
end

-- 计算属性
function doCalcHero(human, attrs)
    if human and human.db and human.db.chengjiu and human.db.chengjiu.attrs then
        for k, v in pairs(human.db.chengjiu.attrs) do
            if v > 0 then
               RoleAttr.updateValue(k, v, attrs)
            end
        end
    end
end

-- 检查特权是否激活
function checkPrivilege(human,priType)
    if not human or not human.db or not human.db.chengjiu then return end
    if human.db.chengjiu.privilege == nil or human.db.chengjiu.privilege[priType] == nil or human.db.chengjiu.privilege[priType] == 0 then
        return 
    end
    return human.db.chengjiu.privilege[priType]
end
--
function initAfterHotTemp()
    local taskID = 402
    local config = ChengjiuExcel[taskID]
    LuaMongo.find(DB.db_char)
    local DBUpdate = {}
	while true do 
	    local data = {}
	    if not LuaMongo.next(DB.db_char, data) then
		    break
	    end
        DBUpdate._id = data._id
        if data.chengjiu.task and
           data.chengjiu.task[taskID] and
           data.chengjiu.task[taskID] == CJ_TASK_STATE_2 and 
           config then
            -- 给特权奖励
            for _,v in pairs(config.privilege) do
                data.chengjiu.privilege = data.chengjiu.privilege or {}
                data.chengjiu.privilege[v[1]] = v[2]
                local human = ObjHuman.onlineUuid[data._id]
                if human then
                    human.db.chengjiu.privilege[v[1]] = v[2]
                else
                    data._id = nil
                    local updateDb = {}
			        updateDb["$set"] = data
			        LuaMongo.update(DB.db_char, DBUpdate, updateDb)
                end
            end
        end
	end
end
